package com.cqupt.service.impl;

import com.cqupt.pojo.SearchInfo;
import com.cqupt.service.SolrService;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SolrServiceImpl implements SolrService {
    // 知识库索引搜索的Url
    private final String solrURL = "http://localhost:8983/solr/knowledge_search";

    @Override
    public Map<String, Object> getQueryResultByNLR(Map<String, Object> params) throws IOException, SolrServerException {
        // 创建 solr 客户端，用于连接 solr 服务器
        HttpSolrClient client = new HttpSolrClient.Builder(solrURL).build();
        SolrQuery solrQuery = new SolrQuery();
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> finalResult = new ArrayList<>();
        // 获取查询参数
        String nlr = (String) params.get("nlr");
        // 删除括号，否则查询会出错
        nlr = nlr.replace("(", "").replace(")", "");
        // 根据是否分页，返回查询的结果
        int pagenum = 0;
        int pagesize = Integer.MAX_VALUE;
        if (params.containsKey("pagenum"))
            pagenum = ((int) params.get("pagenum") - 1) * pagesize;
        if (params.containsKey("pagesize"))
            pagesize = (int) params.get("pagesize");
        if ("".equals(nlr)) solrQuery.set("q", "*:*");
        else solrQuery.set("q", "name_label_resolution:" + nlr);
        solrQuery.setStart(pagenum);
        solrQuery.setRows(pagesize);
        solrQuery.addSort("score", SolrQuery.ORDER.desc);
        // 执行查询
        QueryResponse response = client.query(solrQuery);
        long total = response.getResults().getNumFound();
        // 将返回的结果封装为 SearchInfo 对象
        List<SearchInfo> searchInfoList = response.getBeans(SearchInfo.class);
        // 遍历结果，重新命名，返回前端展示
        for (SearchInfo searchInfo : searchInfoList) {
            Map<String, Object> singleMap = new HashMap<>();
            singleMap.put("knowledgeAppraval", searchInfo.getApproval());
            singleMap.put("approval_man", searchInfo.getApproval_man());
            singleMap.put("common_key", searchInfo.getCommon_key());
            singleMap.put("id", searchInfo.getId());
            singleMap.put("key_", searchInfo.getKnowledgeKeys());
            singleMap.put("knowledgeLabel", searchInfo.getKnowledgeLabel());
            singleMap.put("knowledgeName", searchInfo.getKnowledgeName());
            singleMap.put("knowledgeRes", searchInfo.getResolution());
            singleMap.put("submit_user", searchInfo.getSubmit_user());
            singleMap.put("submit_time", searchInfo.getTime());
            singleMap.put("knowledgeType", searchInfo.getKnowledgeType());
            singleMap.put("problemName", searchInfo.getProblem());
            finalResult.add(singleMap);
        }
        // 提交并关闭
        client.commit();
        client.close();
        resultMap.put("resultData", finalResult);
        resultMap.put("total", total);
        return resultMap;
    }

    /**
     * 添加或更新索引（有则更新，无则添加）
     * @param searchInfo 要填加的对象
     * @throws IOException
     * @throws SolrServerException
     */
    @Override
    public void addAndUpdateIndex(SearchInfo searchInfo) throws IOException, SolrServerException {
        HttpSolrClient client = new HttpSolrClient.Builder(solrURL).build();
        client.addBean(searchInfo);
        client.commit();
        client.close();
    }

    /**
     * 删除索引
     * @param id 索引对应的 id
     * @throws IOException
     * @throws SolrServerException
     */
    @Override
    public void deleteIndexById(String id) throws IOException, SolrServerException {
        HttpSolrClient client = new HttpSolrClient.Builder(solrURL).build();
        client.deleteById(id);
        client.commit();
        client.close();
    }
}
